package main

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	"time"
)

func main() {

	for i := 0; i < 10; i++ {
		go d1_demo()
	}

	time.Sleep(time.Second * 5)
	fmt.Println("done")
}

func d1_demo() {
	config := api.DefaultConfig()
	config.Address = "127.0.0.1:8500"
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}
	// 创建会话
	session := client.Session()
	se := &api.SessionEntry{
		Name:     "my-session",
		TTL:      "10s", // 设置合适的TTL
		Behavior: "delete",
	}
	sessionID, _, err := session.Create(se, nil)
	if err != nil {
		panic(err)
	}
	// 锁的键
	key := "my-key"
	// 获得kv客户端
	kv := client.KV()
	pair := &api.KVPair{
		Key:     key,
		Value:   []byte(sessionID),
		Session: sessionID,
	}

	// 创建一个带锁的key
	acquired, _, err := kv.Acquire(pair, nil)
	if err != nil {
		fmt.Println("lock error")
		panic(err)
	} else if acquired {
		fmt.Println("lock success, sessionID=", sessionID)

		//  模拟处理逻辑
		time.Sleep(time.Second * 2)

		// 释放锁
		b1, _, err := kv.Release(pair, nil)
		if err != nil {
			fmt.Println("unlock failed")
			panic(err)
		} else {
			fmt.Println("unlock success, ", b1)
		}

	} else {
		fmt.Println("lock failed")
	}
}
